<?php
if (!session_id()) {
    session_start();
}
require_once '../../a_config.php';
require_once "{$A_CONFIG['api_include']}";
$conn = connect_to_db();
$err = -1;
$msg = "";

if (isset($_POST['token']) && !empty($_POST["token"]) &&
    isset($_POST['time']) && !empty($_POST["time"]) &&
    isset($_POST['username']) && !empty($_POST["username"]) &&
    isset($_POST['password']) && !empty($_POST["password"])) {
    $key = $A_CONFIG['api_key'];
    $unixtime = $_POST['time'];
    $token = md5($key . $unixtime);
    if ($token == $_POST["token"]) {
        $username = mysql_real_escape_string($_POST["username"]);
        $passwd = mysql_real_escape_string($_POST["password"]);

        $sql = "SELECT `password` FROM `{$A_CONFIG['project_pre']}_backstage_admin_list` WHERE username='$username' and is_del=0 limit 1";
        $res = mysql_query($sql, $conn);
        if (is_resource($res) && mysql_num_rows($res) != 0) {
            $row = mysql_fetch_array($res, MYSQL_ASSOC);
            $database_passwd = $row["password"];
            if ($passwd == $database_passwd) {
                //获取后台管理系统session_key
                $session_key = $A_CONFIG['project_pre'] . 'admin_backstage';
                $admin_status = $session_key . '_status';
                $admin_name = $session_key . '_name';

                $_SESSION[$admin_status] = "loginSuccess";
                $_SESSION[$admin_name] = $username;

                $kmLoginIP = getClientIP();
                $sessionId = session_id();
                $userAgent = isset($_SERVER["HTTP_USER_AGENT"]) ? mysql_real_escape_string($_SERVER['HTTP_USER_AGENT']) : "";//记录浏览器等
                session_write_close();
                $err = 0;
                $msg = "登录成功";
                //记录日志
                $sql = "insert into `zj_login_log` (`login_name`,login_time,sessionid,ip,userAgent) value  ('$username',now(),'$sessionId','$imLoginIP','$userAgent')";
                mysql_query($sql, $conn);

            } else {
                $err = -2;
                $msg = "error2:账号或密码错误";
            }
        } else {
            $err = -3;
            $msg = "error1:账号或密码错误";
        }
    } else {
        $err = -4;
        $msg = "非法请求";
    }
} else {
    $err = -5;
    $msg = "参数错误";
}
if (!$A_CONFIG['is_debug']) {
    $resArr = compact("err", "msg");
} else {
    $resArr = compact("err", "msg", 'sql');
}

$resJson = json_encode_cn($resArr);
echo $resJson;